package com.dark.cms.base.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;

import java.util.*;

/**
 * JSON工具类
 * 
 * @author Devil
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class JSONUtil {
	private static SerializeConfig config = new SerializeConfig();
	static{
		config.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd"));
	}
	
	/**
	 * 降对象转化为JSON格式
	 * @param obj
	 * @return
	 */
	public static String toJSONString(Object obj) {
		if (ValidateUtil.isEmpty(obj))
			return "";
		return JSON.toJSONString(obj, config, SerializerFeature.WriteMapNullValue);
	}

	/**
	 * 将json转化为对象
	 * @param json
	 * @param cls
	 * @return
	 */
	public static Object parseObject(String json, Class cls) {
		if (ValidateUtil.isEmpty(json))
			return null;
		return JSON.parseObject(json, cls);
	}

	public static void main(String[] args) {
		List list = new ArrayList();
		Map hm = new HashMap();
		hm.put("name", "张三");
		hm.put("age", 13);
		hm.put("max", null);
		list.add(hm);
		hm = new HashMap();
		hm.put("name", "李四");
		hm.put("age", 12);
		hm.put("birthday", new Date());
		list.add(hm);
		hm = new HashMap();
		hm.put("wang", "1");
		hm.put("list", list);
		SerializeConfig config = new SerializeConfig();
		config.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd"));
		String json = JSON.toJSONString(hm,config,SerializerFeature.WriteMapNullValue);
		System.out.println(json);
	}
}
